import React, { useState, useEffect } from 'react';
import './index.css';

const Counter = ({ onCheckIn,setTtamp }) => {
    const [currentTime, setCurrentTime] = useState(new Date());

    // 更新时间的函数
    const updateTime = () => {
        setCurrentTime(new Date());
    };

    // 使用useEffect钩子每秒更新一次时间
    useEffect(() => {
        const timer = setInterval(updateTime, 1000);
        return () => clearInterval(timer); // 清除定时器以防止内存泄漏
    }, []);

    // 格式化时间为HH:MM:SS格式
    const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以+1
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        // 保存年月日（可用于其他操作，例如发送到后端）
        const currentDate = `${year}-${month}-${day}`;
        const currentTimeFormatted = `${hours}:${minutes}:${seconds}`;

        // console.log('当前日期:', currentDate); // 可选：用于调试
        // console.log('当前时间:', currentTimeFormatted); // 可选：用于调试

        const reconstructedDate = new Date(year, month - 1, day, hours, minutes);
        const timestamp = reconstructedDate.getTime(); // 单位是毫秒
        setTtamp(timestamp);

        return {
            date: currentDate,
            time: currentTimeFormatted
        };
    };

    const timeData = formatTime(currentTime);

    return (
        <div className="check-in-button" onClick={onCheckIn}>
            <span className="check-in-text">签到</span>
            <span className="check-in-time">{timeData.time}</span>
        </div>
    );
};

export default Counter;